package com.cskaoyan.order.mq.consumer;

import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @Description:
 * @author: jzc
 * @since: 2022/10/28 19:43
 **/
@Component
public class DelayOrderCancelConsumer {


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private StockMapper stockMapper;


    private DefaultMQPushConsumer consumer;
    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("order_delay_cancel_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                long endTime = System.currentTimeMillis();
                // 实现，订单超时自动取消的业务逻辑
                MessageExt message = msgs.get(0);
                String startTimeStr = message.getUserProperty("startTimeStr");
                System.out.println("msg id " + message.getMsgId() + "time span " + (endTime - Long.parseLong(startTimeStr)));
                //获取消息体数据
                byte[] body = message.getBody();
                // 业务逻辑处理数据
                try {
                    String orderId = new String(body, 0, body.length, "utf-8");
                    //2. 去数据库根据OrderId，查询订单转态
                    Order order = orderMapper.selectByPrimaryKey(orderId);
                    //3. 如果订单已经支付，或者已经取消，什么都不做

                    //4. 如果订单仍然是初始化转态，未支付成功，执行自动取消的逻辑
                    //     a. 修改订单的状态为已取消
                    //     b. 访问tb_order_item，查询订单中包含的所有订单商品条目，根据订单条目中商品购买的数量  +stockCount  -lockCount
                    if (order.getStatus()==0){
                        order.setStatus(7);
                        orderMapper.updateByPrimaryKey(order);
                        Example example = new Example(OrderItem.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andEqualTo("orderId",orderId);
                        orderItemMapper.updateStockStatus(2,orderId);
                        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
                        for (OrderItem orderItem : orderItems) {
                            Stock stock = stockMapper.selectStock(orderItem.getItemId());
                            stock.setStockCount((long)orderItem.getNum());
                            stock.setLockCount(-orderItem.getNum());
                            stockMapper.updateStock(stock);
                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        try {
            consumer.subscribe("delay_order_cancel","*");
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

}
